<template>

  <!-- 查询 -->
  <el-card>
    <el-input placeholder="请输入职务名称" v-model="Search.RoleName" style="width: 200px;margin-right: 10px;"></el-input>
    <el-button type="primary" @click="GetRoleList">搜索</el-button>
    <el-button @click="ResetSearch">重置</el-button>
  </el-card>

  <br>


  <el-card>
  <!-- 新增职务 -->
      <el-button type="primary" @click="Adddelog(1)">新增职务</el-button>
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%">
      <el-table-column fixed prop="RoleId" label="编号" />
      <el-table-column prop="RoleName" label="职务名称"  />
      <el-table-column prop="Status" label="状态"  >
        <template #default="scope">
          <el-tag v-if="scope.row.Status==0" type="success">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
        </el-table-column>
        <el-table-column prop="Desc" label="角色描述"  />
      <el-table-column prop="NumPeople" label="成员数量"  />
      <el-table-column prop="DepartmentDesc" label="部门描述"  />
      <el-table-column prop="UpdateTime" label="更新时间"  >
        <template #default="scope">
          {{ moment(scope.row.UpdateTime).format('YYYY-MM-DD HH:mm:ss')}}
        </template>
        </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="OpenSetPermissionDialog(scope.row.RoleId)">
            设置权限
          </el-button>
          <el-button link type="primary" size="small" @click="Adddelog(scope.row)">编辑职务</el-button>
          <el-button link type="primary" size="small" @click="AddRoleForAccount(scope.row.RoleId,scope.row.RoleName)">添加人员</el-button>
          <el-button link type="primary" size="small" @click="OpenDialog(scope.row.RoleId)">设置状态</el-button>
          <el-button link type="danger" size="small" @click="DeleteRoleId(scope.row.RoleId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    </el-card>

    <!-- 分页 -->
    <tr>
      <td>
        <el-pagination
            v-model:current-page="Search.PageIndex"
            v-model:page-size="Search.PageSize"
            :page-sizes="[9, 18, 27, 36]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="Search.TotalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
      </td>
    </tr>

    <!-- 设置状态对话框 -->
    <el-dialog v-model="dialogFormVisible" title="设置状态" width="500">
    <el-form :model="EditStatus">
      <el-form-item label="Zones">
        <el-select v-model="EditStatus.Status" placeholder="请选择">
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="UpdateStatus">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增职务对话框 -->
  <el-dialog v-model="dialogFormAddRoleVisible" :title="addrole" width="500">
    <el-form :model="RoleList">
      <el-form-item label="职务名称" >
        <el-input v-model="RoleList.RoleName" autocomplete="off" placeholder="请输入职务名称" />
      </el-form-item>
      <el-form-item label="职务描述" prop="desc">
      <el-input v-model="RoleList.RoleDesc" type="textarea" placeholder="请输入职务描述"/>
    </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormAddRoleVisible = false">取消</el-button>
        <el-button type="primary" @click="AddRoledialog">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加人员对话框 -->
  <el-dialog v-model="dialogFormAddAccountVisible" title="添加人员" width="500">
    <el-form :model="AddRoleAndAccount">
  
      <el-form-item label="职务名称">
        <el-input v-model="RoleName" autocomplete="off" disabled/>
      </el-form-item>

      <el-form-item label="主管人员">
      <el-cascader
        v-model="AddRoleAndAccount.AccountId"
        :options="DepartmentPeopleList"
        :props="props"
      />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormAddAccountVisible = false">取消</el-button>
        <el-button type="primary" @click="AddAccountdialog">保存</el-button>
      </div>
    </template>
  </el-dialog>


  <!-- 设置权限对话框 -->
  <el-dialog v-model="dialogFormSetPermissionVisible" title="设置权限" width="500">
    <!-- 我添加了表格引用 ref="permissionTableRef"，这样可以通过 permissionTableRef.value 访问表格组件实例 -->
    <el-table :data="PermissionList" stripe style="width: 100%" ref="permissionTableRef">
      <el-table-column prop="PermissionsId" label="编号" width="100" align="center" />
      <el-table-column prop="PermissionsName" label="功能类型" width="200" align="center" />
      <el-table-column  type="selection" width="200"  align="left" />
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormSetPermissionVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveChangesPermissions">保存</el-button>
      </div>
    </template>
  </el-dialog>

  </template>
  
  <script lang="ts" setup>
  import { ref,reactive,onMounted } from 'vue';
  import { GetRoleDepartmentRelationList,GetPeopleFromDepartment,GetPermissionList,GetRoleIdForShowPermissions } from '@/api/Readapi';
  import { DeleteRole,UpdateStatusRole,AddRole,AddRoleToAccount,UpdateRole,GetRoleIdToUpdatePermissions } from '@/api/Writeapi';
  import moment from 'moment';
  import { ElMessageBox, ElMessage } from 'element-plus';

  //挂载
  onMounted(()=>{
    GetRoleList()
  })

    //接口返回数据
  interface ApiResponse {
    code: number
    msg: string
    data: any
  }

  //#region 角色列表
  //表格数据
  const tableData = ref([]);
  //搜索
  const Search = reactive({
    PageIndex:1,
    PageSize:9,
    RoleName:'',
    TotalCount:0,
    TotalPage:0
  })
  //重置按钮
  const ResetSearch = () => {
    Search.RoleName = ''
    GetRoleList()
  }


  const GetRoleList=async()=>{
    const res = await GetRoleDepartmentRelationList(Search)as unknown as ApiResponse;
    if(res.code==200){
      tableData.value = res.data.data
      Search.TotalCount = res.data.TotalCount
      Search.TotalPage = res.data.TotalPage
    }
  }

  //分页
  const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  Search.PageSize = val
  GetRoleList()
}

  //分页
  const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  Search.PageIndex = val
  GetRoleList()
}

  //#endregion

  //#region 删除职务
  const DeleteRoleId = async (id:number)=>{
    ElMessageBox.confirm(
    '确定删除该职务吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res = await DeleteRole(id) as unknown as ApiResponse;
      if(res.code==200){
        ElMessage.success('删除成功')
        GetRoleList()
      }
      else{
        ElMessage.error(res.msg)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除该职务',
      })
    })
  }
  //#endregion

  //#region 修改状态
  const dialogFormVisible = ref(false)

  const EditStatus = reactive({
    RoleId:0,
    Status:''
  })

  const OpenDialog=(id:number)=>{
    dialogFormVisible.value = true
    EditStatus.RoleId = id
  }

  const UpdateStatus = async()=>{

    const res = await UpdateStatusRole(EditStatus) as unknown as ApiResponse; 

    if(res.code==200){
      ElMessage.success('修改状态成功')
      GetRoleList()
      dialogFormVisible.value = false
    }
    else{
      ElMessage.error(res.msg)
    }
  }
  //#endregion

  //#region 新增 || 编辑职务
  const RoleList = reactive({
    RoleId:0,
    RoleName:'',
    Status:0,
    RoleDesc:'',
    IsDeleted:false
  })

  //新增 || 编辑职务对话框

  
  const dialogFormAddRoleVisible = ref(false)

  let addrole = "新增职务"

  const Adddelog=(type:any)=>{

    if(type==1){
      addrole = "新增职务"

      RoleList.RoleId = 0
      RoleList.RoleName = ''
      RoleList.RoleDesc = ''
      RoleList.Status = 0
      RoleList.IsDeleted = false

    }
    else{
      addrole = "编辑职务"
      RoleList.RoleId = type.RoleId
      RoleList.RoleName = type.RoleName
      RoleList.RoleDesc = type.Desc
    }
    dialogFormAddRoleVisible.value = true
  }

 //角色新增对话框确定按钮
  const AddRoledialog = async()=>{
    //角色id为0是新增 否则是编辑
    if(RoleList.RoleId==0){
      if(RoleList.RoleName=='' || RoleList.RoleDesc==''){
        ElMessage.error('职务名称和职务描述不能为空')
        return
      }
      const res = await AddRole(RoleList) as unknown as ApiResponse;
      if(res.code==200){
        ElMessage.success('新增职务成功')
        GetRoleList()
        dialogFormAddRoleVisible.value = false
      }
      else{
        ElMessage.error(res.msg)
      }
    }
    else{
      const res = await UpdateRole(RoleList) as unknown as ApiResponse;
      if(res.code==200){
        ElMessage.success('编辑职务成功')
        GetRoleList()
        dialogFormAddRoleVisible.value = false
      }
      else{
        ElMessage.error(res.msg)
      }
    }
  }
  //#endregion

  //#region 添加人员
  const dialogFormAddAccountVisible = ref(false)

  const AddRoleAndAccount = reactive({
    RoleId:0,
    AccountId:[]
  })

  //职务名称
  const RoleName:any = ref([])

  const AddRoleForAccount=(id:number,name:string)=>{
    dialogFormAddAccountVisible.value = true
    GetDepartmentPeopleList()
    AddRoleAndAccount.RoleId = id
    RoleName.value = name

  }

  //添加人员对话框确定按钮
  const AddAccountdialog = async()=>{

    console.log(AddRoleAndAccount)

    if(AddRoleAndAccount.AccountId.length==0){
      ElMessage.error('请选择主管人员')
      return
    }

    const res = await AddRoleToAccount(AddRoleAndAccount)
      ElMessage.success('添加人员成功')
      GetRoleList()
      dialogFormAddAccountVisible.value = false
  }

  //获取部门人员列表
  const DepartmentPeopleList = ref<any[]>([])
  //获取部门人员列表
  const GetDepartmentPeopleList=async()=>{
    const res = await GetPeopleFromDepartment() as unknown as ApiResponse;
    if(res.code==200){
      DepartmentPeopleList.value = res.data
    }
  }

  //级联人员可以多选且只获取最后一级数据
  const props = { multiple: true, emitPath:false }
  //#endregion

  //#region 设置权限
  
  //权限列表
  const PermissionList = ref([])

  //当前操作的角色ID
  const currentRoleId = ref(0)

  const dialogFormSetPermissionVisible = ref(false)
  const OpenSetPermissionDialog=(id:number)=>{

    //打开弹出框
    dialogFormSetPermissionVisible.value = true
    
    //保存当前角色ID
    currentRoleId.value = id

    //权限列表
    GetPermission();

    //获取角色id
    GetRoleIdShowPermissions(id);
  }

  //权限列表
  const GetPermission=async()=>{
    const res = await GetPermissionList() as unknown as ApiResponse;
    if(res.code==200){
      PermissionList.value = res.data
    }
    else{
      ElMessage.error(res.msg)
    }
  }

  //角色Id对应的权限
  const DetailsPermissionsList = ref([])
  //定义该响应式数据为了访问 组件的实例
  const permissionTableRef = ref()

  //通过角色Id加载对应的权限
  const GetRoleIdShowPermissions=async(id:any)=>{
    const res = await GetRoleIdForShowPermissions(id) as unknown as ApiResponse;

    if(res.code==200){
      DetailsPermissionsList.value = res.data
      
      // 设置已有权限的选中状态
      // 等待DOM更新后再设置选中状态
      //setTimeout 是 JavaScript 里的一个定时器函数，用来"延迟"执行某段代码。
      setTimeout(() => {
        
        // 获取角色已有的权限ID列表
        const rolePermissionIds: number[] = []
        
        // 根据返回的数据结构提取权限ID
        if (res.data) {
          // 遍历data对象，查找所有包含PermissionsId的项
          //这里的Key获取到的是键名 键名为 "0" "1" "2"
          for (const key in res.data) {
            const item = res.data[key] //获取对应的键值
              rolePermissionIds.push(item.PermissionsId) //将获取到的权限Id给Push进数组里面
          }
        }
        
        // 遍历权限列表，设置已有权限的选中状态
        PermissionList.value.forEach((row: any) => {
          //Includes 判断值是否在rolePermissionIds数组中
          if (rolePermissionIds.includes(row.PermissionsId)) {
            //这句的意思是：通过 Element Plus 的表格组件实例（permissionTableRef.value），
            // 调用 toggleRowSelection 方法，把当前这行（row）设置为"选中"状态（即复选框打勾）。
            permissionTableRef.value?.toggleRowSelection(row, true)
          }
        })
        //100 为setTimeout 函数的延迟
      }, 100)
      
    }
    else{
      ElMessage.error(res.msg)
    }
  }



  //保存
 const SaveChangesPermissions=async()=>{
  //定义数组获取重新选择的权限Id
  const Permissions:number []=[]

  // 获取表格中所有选中的行
  //getSelectionRows方法会返回表格中所有被选中的行数据，然后我们遍历这些行数据，
  // 提取每行的 PermissionsId 属性，添加到 Permissions 数组中。
  const selectedRows = permissionTableRef.value.getSelectionRows()
  
  // 将选中行的权限ID添加到数组中
  selectedRows.forEach((row: any) => {
    Permissions.push(row.PermissionsId)
  })
  
  
  // 构建参数对象 - 确保参数名称与后台接口一致
  const data = {
    RoleId: currentRoleId.value,
    PermissionsId: Permissions // 后台接收的是List<int>类型
  }
  
  // 调用API保存权限设置
  const res = await GetRoleIdToUpdatePermissions(data) as unknown as ApiResponse;
  if(res.code==200){
    ElMessage.success('权限设置成功')
    dialogFormSetPermissionVisible.value = false
  } else {
    ElMessage.error(res.msg)
  }
 }

  //#endregion

  </script>
  